/*
 * =====================================================================================
 *
 *       Filename:  cmdSet.c
 *
 *    Description:  command set using AVL tree.
 *
 *        Version:  0.1
 *        Created:  2017/02/14 16:17:50
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Brook L. (), Brook_L@163.com
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include "cmdSet.h"

AvlTree gCmdSet;

static void cmd1Process(char *cmd) {
    printf("The command is: \"%s\"\n", cmd);
}

static void cmd2Process(char *cmd) {
    printf("The command is: \"%s\"\n", cmd);
}

static void cmd3Process(char *cmd) {
    printf("The command is: \"%s\"\n", cmd);
}

// All commands and their process
static Cmd cmds[] = {
    {"cmd1", cmd1Process},
    {"cmd2", cmd2Process},
    {"cmd3", cmd3Process},
};

// Init command set, init AVL tree, and build command tree
void cmdSetInit(void) {
    int i;

    avlInit(&gCmdSet, cmdCompare, cmdInsertMatchProcess, cmdTravProcess);

    for (i = 0; i < sizeof(cmds) / sizeof(Cmd); i++) {
        gCmdSet.root = avlInsert(&gCmdSet, gCmdSet.root, &cmds[i]);
    }
}

/**
 * cmdSetExe - Execute the input command
 * @cmdStr - input command
 */
void cmdSetExe(char *cmdStr) {
    AvlNode *node = NULL;
    Cmd cmd;

    cmd.cmd = cmdStr;
    node = avlFind(&gCmdSet, gCmdSet.root, &cmd);
    if (node != NULL) {
        node->content.process(node->content.cmd);
    } else {
        printf("Error: Command not found!\n");
    }
}
